<script setup lang="tsx">
import { reactive, ref, watch, onMounted, unref } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElCheckbox, ElLink, ElMessage } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
// import { getTestRoleApi, getAdminRoleApi } from '@/api/login'
// import { useAppStore } from '@/store/modules/app'
import { useAccountStore } from '@/store/modules/account'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserLoginType, LoginItem } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { useUserStore } from '@/store/modules/user'
import { BaseButton } from '@/components/Button'
import { SliderUnlock } from '@/components/SliderUnlock'
import { getEncryptCode, getInfoApi, login } from '@/api/common/account'
import { isMobile } from '@/utils'
import JSEncrypt from 'jsencrypt'

const { required } = useValidator()

const emit = defineEmits(['to-register'])

const accountStore = useAccountStore()

const userStore = useUserStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { t } = useI18n()

const rules = {
  username: [required()],
  password: [required()]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold text-center w-[100%]">{t('login.login')}</h2>
        }
      }
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    // value: 'admin',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: 'admin or test'
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    // value: 'admin',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: 'admin or test'
    }
  },
  {
    field: 'verify',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          if (isMobileBrowser.value) {
            return <></>
          } else {
            return (
              <>
                <div class="flex w-[100%]">
                  <SliderUnlock
                    show-text="请拖动滑块解锁"
                    success-text="验证通过  √"
                    failure-text="验证失败  ×"
                    forbidden-text="重试次数太多已被禁用"
                    init-time={captchaInit.value}
                    class="w-[100%]"
                    onCaptcha_status={handleCaptcha}
                  />
                </div>
              </>
            )
          }
        }
      }
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <ElCheckbox v-model={remember.value} label={t('login.remember')} size="small" />
                <ElLink type="primary" underline={false}>
                  {t('login.forgetPassword')}
                </ElLink>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <BaseButton
                  loading={loading.value}
                  type="primary"
                  class="w-[100%]"
                  onClick={signIn}
                >
                  {t('login.login')}
                </BaseButton>
              </div>
            </>
          )
        }
      }
    }
  }
])

const remember = ref(userStore.getRememberMe)

const initLoginInfo = () => {
  const loginInfo = userStore.getLoginInfo
  if (loginInfo) {
    const { username, password } = loginInfo
    setValues({ username, password })
  }
}
const api_readEncrypt = async () => {
  const data = await getEncryptCode()
  if (data.MsgCode === '200') {
    const dtItem = JSON.parse(data.MsgData)
    encryptValue.value = dtItem.Id
    encryptPubKey.value = dtItem.Code
  } else {
    console.log(data.MsgError)
  }
}

onMounted(async () => {
  api_readEncrypt()
  initLoginInfo()
})

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose, setValues } = formMethods

const loading = ref(false)

const redirect = ref<string>('')

const encryptValue = ref<string>('')

const encryptPubKey = ref<string>('')

const captchaValue = ref<string>('')

const isMobileBrowser = ref<boolean>(isMobile())

const captchaInit = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
const createLoginItem = (formData: UserLoginType): LoginItem => {
  const jse = new JSEncrypt()
  jse.setPublicKey(encryptPubKey.value)
  return {
    LoginId: formData.username,
    CaptchaId: captchaValue.value,
    EncryptId: encryptValue.value, // 使用响应式值
    IsMobile: false,
    LoginPwd: jse.encrypt(formData.password) // 加密密码
  }
}
const handleCaptcha = (data: { MsgCode: string; MsgData: string }) => {
  if (data.MsgCode === '200') {
    captchaValue.value = data.MsgData
  } else {
    captchaValue.value = ''
  }
}
// 登录
const signIn = async () => {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<UserLoginType>()
      const dataForm: LoginItem = createLoginItem(formData)

      try {
        const loginData = await login(dataForm) // 登录接口

        if (loginData.MsgCode === '200') {
          // 是否记住我
          if (unref(remember)) {
            userStore.setLoginInfo({
              username: formData.username,
              password: formData.password
            })
          } else {
            userStore.setLoginInfo(undefined)
          }
          userStore.setRememberMe(unref(remember))

          const info = await getInfoApi({ smId: accountStore.smId }) // 获取用户信息

          if (info.MsgCode === '200') {
            const dtItem = JSON.parse(info.MsgData)
            if (dtItem.IsAdmin) {
              userStore.setUserInfo(dtItem)
              accountStore.setID(dtItem.Id)
              accountStore.setName(dtItem.Name)
              accountStore.setIsPower(true)
              accountStore.setRights(dtItem.Rights)
              accountStore.setSettings(dtItem.Settings)
            } else {
              ElMessage.error('禁止非法操作')
            }
          } else {
            ElMessage.error(info.MsgError)
          }

          await permissionStore.generateRoutes('static').catch(() => {})
          permissionStore.getAddRouters.forEach((route) => {
            addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
          })
          permissionStore.setIsAddRouters(true)
          push({ path: redirect.value || permissionStore.addRouters[0].path })
        } else {
          formData.username = ''
          formData.password = ''
          captchaValue.value = ''
          captchaInit.value = new Date().getTime().toString()
        }
        // if (res) {
        //   // 是否记住我
        //   if (unref(remember)) {
        //     userStore.setLoginInfo({
        //       username: formData.username,
        //       password: formData.password
        //     })
        //   } else {
        //     userStore.setLoginInfo(undefined)
        //   }
        //   userStore.setRememberMe(unref(remember))
        //   userStore.setUserInfo(res.data)
        //   // 是否使用动态路由
        //   if (appStore.getDynamicRouter) {
        //     getRole()
        //   } else {
        //     await permissionStore.generateRoutes('static').catch(() => {})
        //     permissionStore.getAddRouters.forEach((route) => {
        //       addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
        //     })
        //     permissionStore.setIsAddRouters(true)
        //     push({ path: redirect.value || permissionStore.addRouters[0].path })
        //   }
        // }
      } finally {
        loading.value = false
      }
    }
  })
}

// 获取角色信息
// const getRole = async () => {
//   const formData = await getFormData<UserType>()
//   const params = {
//     roleName: formData.username
//   }
//   const res =
//     appStore.getDynamicRouter && appStore.getServerDynamicRouter
//       ? await getAdminRoleApi(params)
//       : await getTestRoleApi(params)
//   if (res) {
//     const routers = res.data || []
//     userStore.setRoleRouters(routers)
//     appStore.getDynamicRouter && appStore.getServerDynamicRouter
//       ? await permissionStore.generateRoutes('server', routers).catch(() => {})
//       : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {})

//     permissionStore.getAddRouters.forEach((route) => {
//       addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
//     })
//     permissionStore.setIsAddRouters(true)
//     push({ path: redirect.value || permissionStore.addRouters[0].path })
//   }
// }

// 去注册页面
// const toRegister = () => {
//   emit('to-register')
// }
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid) w-380px"
    @register="formRegister"
  />
</template>

<style lang="less" scoped>
// @prefix-cls: ~'@{elNamespace}-form-item';
// .@{prefix-cls} {
//   :deep(&--large) {
//     margin-bottom: 0;
//   }
// }
:deep(.@{elNamespace}-form-item--large) {
  margin-bottom: 16px;
}
</style>
